<template>
  <div>
    <TopFilter :list="topFilterList" :cols="3" :rows="2" :label-width="90" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <FilterTable
      ref="table"
      columnsRef="jsgdTable"
      :columns="columns"
      :dataSource="dataSource"
      :params="fetchParams"
      :fetchapi="fetchApi"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChangeHandle"
    >
      <template slot="controls">
        <el-button v-if="true" size="small" type="primary" @click="closeBalance">关单</el-button>
        <el-button v-if="canCancel" size="small" type="primary" @click="cancelCloseBalance">取消关单</el-button>
      </template>
    </FilterTable>
    <drawer title="结算单明细" :visible.sync="detailVisible" :width="920" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <Detail ref="detail" @close="closeHandler" />
    </drawer>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { authority } from '@/utils/authMixin';
import { getBalanceList, closeBalance, cancelCloseBalance, getUserListSelect, getAllUser } from '@/api/finance/repairFinance/closeBalance';
import Detail from '@/pages/finance/repairFinance/receivables/detail';
import { formatDat } from '@/utils/validate'; // 时间戳转换成年月日
import { isAuthorized } from '@/utils/index';
export default {
  name: 'closeBalance',
  components: { Detail },
  mixins: [dictionary, authority],
  data() {
    this.BaseTable = null;
    return {
      topFilterList: this.createTopFilterList(),
      fetchParams: { xhrAbort: true },
      visible: false,
      dialogTitle: '',
      fetchApi: getBalanceList,
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      dataSource: [],
      selectedRows: [],
      detailVisible: false,
      canCancel: true,
      serviceAdvisorData: [],
      is_auth_rono: false, // 是否可以关闭工单
      is_auth_salesno: false // 是否可以关闭销售单
    };
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.initSelect();
    // this.serachService();
    this.getAuth(); // 权限
  },
  methods: {
    getAuth() {
      // 是否可以关闭工单
      if (isAuthorized('1314', '13141006')) {
        this.is_auth_rono = true;
      } else {
        this.is_auth_rono = false;
      }
      // 是否可以关闭配件销售单
      if (isAuthorized('1314', '13141007')) {
        this.is_auth_salesno = true;
      } else {
        this.is_auth_salesno = false;
      }
    },
    async initSelect() {
      // 服务顾问
      this.topFilterList.find(item => item.fieldName === 'serviceAdvisor').itemList = (await getUserListSelect()).data.map(x => ({ value: x.userId, text: x.employeeName }));
      // employeeName翻译
      this.columns.find(x => x.dataIndex === 'OBLIGATED_OPERATOR').editItems = (await getAllUser()).data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
      this.columns.find(x => x.dataIndex === 'BALANCE_HANDLER').editItems = (await getAllUser()).data.map(x => ({ text: x.employeeName, value: x.userId + '' }));

      this.columns.find(x => x.dataIndex === 'SERVICE_ADVISOR').editItems = (await getUserListSelect()).data.map(x => ({ text: x.employeeName, value: x.userId+'' }));
      this.columns.find(x => x.dataIndex === 'LOCK_USER').editItems = (await getAllUser()).data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '工单号',
          fieldName: 'roNo',
          placeholder: '工单号...'
        },
        {
          type: 'INPUT',
          label: '备件销售单号',
          fieldName: 'salesPartNo',
          placeholder: '备件销售单号...'
        },
        {
          type: 'INPUT',
          label: '结算单号',
          fieldName: 'balanceNo',
          placeholder: '结算单号...'
        },
        {
          type: 'RANGE_DATE',
          label: '结算日期',
          fieldName: 'balanceBegin|balanceEnd',
          initialValue: [formatDat(new Date()), formatDat(new Date())],
          placeholder: '选择日期'
        },
        {
          type: 'SELECT',
          label: '是否关单',
          fieldName: 'balanceClose',
          placeholder: '请选择...',
          initialValue: 10041002,
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '是否结清',
          fieldName: 'payOff',
          placeholder: '请选择...',
          itemList: this.createDictList('1004')
        },
        // {
        //   type: 'SELECT',
        //   label: '已全部开票',
        //   fieldName: 'invoiceTag',
        //   placeholder: '请选择...',
        //   itemList: this.createDictList('1004')
        // },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license',
          placeholder: '车牌号...',
          showOverflowTooltip: true
        },
        {
          type: 'SELECT',
          label: '服务顾问',
          fieldName: 'serviceAdvisor',
          placeholder: '请选择...',
          itemList: []
        },
        {
          type: 'RANGE_DATE',
          label: '开单日期',
          fieldName: 'roBegin|roEnd',
          placeholder: '选择日期'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: '',
          width: 70,
          fixed: 'left',
          render: props => {
            return (
              <div>
                <el-tooltip class="item" effect="dark" content="结算单明细" placement="top-start">
                  <el-button size="small" icon="el-icon-document" type="text" onClick={() => this.detail(props.row)}>
                    明细
                  </el-button>
                </el-tooltip>
              </div>
            );
          }
        },
        {
          title: '是否关单',
          dataIndex: 'BALANCE_CLOSE',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{props.row.BALANCE_CLOSE == null ? '否' : this.createDictText(props.row.BALANCE_CLOSE, '1004')}</span>;
          }
        },
        {
          title: '关单日期',
          dataIndex: 'BALANCE_CLOSE_TIME',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '关单人',
          dataIndex: 'OBLIGATED_OPERATOR',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: [],
          filterType: 'input'
        },
        {
          title: '工单号',
          dataIndex: 'RO_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '结算单号',
          dataIndex: 'BALANCE_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '结算员',
          dataIndex: 'BALANCE_HANDLER',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: [],
          filterType: 'input'
        },
        {
          title: '收款金额',
          dataIndex: 'RECEIVE_AMOUNT',
          sorter: true,
          filter: true,
          align: 'right',
          filterType: 'input',
          render: props => {
            return <span>{props.row.RECEIVE_AMOUNT.toFixed(2)}</span>;
          }
        },
        {
          title: '去零金额',
          dataIndex: 'SUB_OBB_AMOUNT',
          sorter: true,
          filter: true,
          align: 'right',
          filterType: 'input',
          render: props => {
            return <span>{props.row.SUB_OBB_AMOUNT.toFixed(2)}</span>;
          }
        },
        {
          title: '减免金额',
          dataIndex: 'DERATE_AMOUNT',
          sorter: true,
          filter: true,
          align: 'right',
          filterType: 'input',
          precision: 2
          //  render: props => {
          //   return <span>{props.row.DERATE_AMOUNT.toFixed(2)}</span>;
          // }
        },
        {
          title: '是否含索赔',
          dataIndex: 'HAVE_CLAIM_TAG',
          sorter: true,
          filter: true,
          filterType: 'input',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.HAVE_CLAIM_TAG, '1004')}</span>;
          }
        },
        {
          title: '索赔工时费',
          dataIndex: 'LABOUR_REAL_SUM_CLAIM',
          sorter: true,
          filter: true,
          align: 'right',
          filterType: 'input',
          precision: 2
        },
        {
          title: '索赔材料费',
          dataIndex: 'REPAIR_PART_REAL_SUM_CLAIM',
          sorter: true,
          filter: true,
          align: 'right',
          filterType: 'input',
          precision: 2
        },
        {
          title: '工时费',
          dataIndex: 'LABOUR_AMOUNT',
          sorter: true,
          filter: true,
          precision: 2,
          align: 'right',
          filterType: 'input'
        },
        {
          title: '材料费',
          dataIndex: 'REPAIR_PART_AMOUNT',
          sorter: true,
          filter: true,
          precision: 2,
          align: 'right',
          filterType: 'input'
        },
        {
          title: '是否结清',
          dataIndex: 'PAY_OFF',
          sorter: true,
          filter: true,
          filterType: 'input',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.PAY_OFF, '1004')}</span>;
          }
        },
        {
          title: '结算时间',
          dataIndex: 'BALANCE_TIME',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '结清日期',
          dataIndex: 'SQUARE_DATE',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '开单日期',
          dataIndex: 'RO_CREATE_DATE',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '工单状态',
          dataIndex: 'RO_STATUS',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8049'),
          render: props => {
            return <span>{this.createDictText(props.row.RO_STATUS, '8049')}</span>;
          }
        },
        {
          title: '维修类型',
          dataIndex: 'REPAIR_TYPE_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车牌号',
          dataIndex: 'LICENSE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车主编号',
          dataIndex: 'OWNER_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车主',
          dataIndex: 'OWNER_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '服务顾问',
          dataIndex: 'SERVICE_ADVISOR',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: [],
          filterType: 'input',
          // render: props => {
          //   return <span>{Number(props.row.SERVICE_ADVISOR)}</span>;
          // }
        },
        {
          title: '销售单号',
          dataIndex: 'SALES_PART_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户代码',
          dataIndex: 'CUSTOMER_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户名称',
          dataIndex: 'CUSTOMER_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: 'VIN',
          dataIndex: 'VIN',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '发动机号',
          dataIndex: 'ENGINE_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '品牌',
          dataIndex: 'BRAND',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '车系',
          dataIndex: 'SERIES',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '车型',
          dataIndex: 'MODEL',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '锁定人',
          dataIndex: 'LOCK_USER',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: [],
          filterType: 'input'
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
        // {
        //   title: '索赔申请单号',
        //   dataIndex: 'CLAIM_NO',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // }
      ];
    },
    detail(data) {
      this.detailVisible = true;
      setTimeout(() => {
        this.$refs.detail.openModel(data);
      }, 150);
    },
    closeHandler(val) {
      this.detailVisible = val;
    },
    // 搜索回调
    changeHandle(data) {
      console.log(data, 'data');
      // 根据搜索条件调用列表
      this.fetchParams = Object.assign({}, data, { xhrAbort: false });
    },
    // 点击展开收起重新计算table高度
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    // 结算关单
    async closeBalance() {
      if (!this.selectedRows.length) {
        return this.$notify({
          title: '提示信息',
          message: '请 选 择 表 格 数 据 ',
          type: 'error'
        });
      }
      let flag = true;
      this.selectedRows.forEach(item => {
        if (flag) {
          if (item.RO_NO !== '' && item.SALES_PART_NO !== '') {
            if (this.is_auth_rono && !this.is_auth_salesno) {
              this.$message({
                type: 'warning',
                message: '您没有关闭销售单的权限!'
              });
              flag = false;
              return;
            } else if (!this.is_auth_rono && this.is_auth_salesno) {
              this.$message({
                type: 'warning',
                message: '您没有关闭工单的权限!'
              });
              flag = false;
              return;
            } else if (!this.is_auth_rono && !this.is_auth_salesno) {
              this.$message({
                type: 'warning',
                message: '您没有关单的权限!'
              });
              flag = false;
              return;
            }
          } else if (item.RO_NO !== '' && item.SALES_PART_NO === '') {
            if (!this.is_auth_rono) {
              this.$message({
                type: 'warning',
                message: '您没有关闭工单的权限!'
              });
              flag = false;
              return;
            }
          } else if (item.RO_NO === '' && item.SALES_PART_NO !== '') {
            if (!this.is_auth_salesno) {
              this.$message({
                type: 'warning',
                message: '您没有关闭销售单的权限!'
              });
              flag = false;
              return;
            }
          } else {
            return;
          }
        }
      });
      if (flag) {
        this.closeBalanceFun();
      }

      // if (this.selectedRows[0].RO_NO !== '' && this.selectedRows[0].SALES_PART_NO !== '') {
      //   if (this.is_auth_rono && !this.is_auth_salesno) {
      //     this.$message({
      //       type: 'warning',
      //       message: '您没有关闭销售单的权限!'
      //     });
      //   } else if (!this.is_auth_rono && this.is_auth_salesno) {
      //     this.$message({
      //       type: 'warning',
      //       message: '您没有关闭工单的权限!'
      //     });
      //   } else if (!this.is_auth_rono && !this.is_auth_salesno) {
      //     this.$message({
      //       type: 'warning',
      //       message: '您没有关单的权限!'
      //     });
      //   } else {
      //     this.closeBalanceFun();
      //   }
      // } else if (this.selectedRows[0].RO_NO !== '' && this.selectedRows[0].SALES_PART_NO === '') {
      //   if (!this.is_auth_rono) {
      //     this.$message({
      //       type: 'warning',
      //       message: '您没有关闭工单的权限!'
      //     });
      //   } else {
      //     this.closeBalanceFun();
      //   }
      // } else if (this.selectedRows[0].RO_NO === '' && this.selectedRows[0].SALES_PART_NO !== '') {
      //   if (!this.is_auth_salesno) {
      //     this.$message({
      //       type: 'warning',
      //       message: '您没有关闭销售单的权限!'
      //     });
      //   } else {
      //     this.closeBalanceFun();
      //   }
      // } else {
      //   return;
      // }
    },
    // 调用关单的接口
    closeBalanceFun() {
      this.$confirm('确定关单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let params = {};
          params['closeBalanceOrderList'] = this.selectedRows;
          let res = await closeBalance(params);
          if (res.resultCode == 200) {
            this.$notify.success({ title: '提示信息', message: '结算关单成功!' });
          }
          this.fetchParams = { ...this.fetchParams };
        })
        .catch(() => {});
    },
    // 结算关单
    async cancelCloseBalance() {
      if (!this.selectedRows.length) {
        return this.$notify({
          title: '提示信息',
          message: '请 选 择 表 格 数 据 ',
          type: 'error'
        });
      }
      this.$confirm('确定取消关单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let params = {};
          params['closeBalanceOrderList'] = this.selectedRows;
          let res = await cancelCloseBalance(params);
          if (res.resultCode == 200) {
            this.$notify.success({ title: '提示信息', message: '取消关单成功!' });
          }
          this.fetchParams = { ...this.fetchParams };
        })
        .catch(() => {});
    },
    selectChangeHandle(rows) {
      this.selectedRows = rows;
    }
  }
};
</script>

<style scoped></style>
